package me.caofeng.service;

import com.alipay.demo.trade.utils.ZxingUtils;
import me.caofeng.enums.ResponseCode;
import me.caofeng.pojo.Response;
import me.caofeng.service.api.IFileService;
import me.caofeng.util.Constant;
import me.caofeng.util.PropertiesUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Copyright © 2017曹峰. All rights reserved.
 *
 * @Prject: mall
 * @Package: me.caofeng.service
 * @Description:
 * @Author: 曹峰 blog.caofeng.me
 * @Date: 2017-06-21 23:20
 * @Version: V1.0
 */
@Service
public class FileService implements IFileService{
    private static Logger LOGGER = LogManager.getLogger(FileService.class);

    @Override
    public Response<List<String>> saveFile(List<MultipartFile> files, String category,String path) {

        List<String> fileNames = new ArrayList<>(files.size());
        for (MultipartFile multipartFile : files){
            String originalFilename = multipartFile.getOriginalFilename();
            String extensionName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            String fileName = UUID.randomUUID().toString().replace("-","")+"."+extensionName;
            LOGGER.info("上传文件 原始文件名 {},文件路径 {},新文件名 {}",originalFilename,path,fileName);
            File targetFile = new File(path,fileName);
            LOGGER.debug(targetFile);
            LOGGER.debug(targetFile.getAbsolutePath());
            try {
                multipartFile.transferTo(targetFile);
                fileNames.add(category+fileName);
            } catch (IOException e) {
                LOGGER.error("上传文件异常" + originalFilename);
                LOGGER.error(e);
            }
        }

        if (fileNames.size() != files.size()){
            return Response.response(ResponseCode.ERROR,"保存文件失败",null);
        }

        return Response.response(ResponseCode.SUCCESS,"图片上传成功",fileNames);
    }

    @Override
    public Response<String> saveQrCode(String qrCode,String orderId) {
        String path = PropertiesUtil.getProperty(Constant.IMAGE_QRCODE)+orderId+".png";
        try {
            File file = ZxingUtils.getQRCodeImge(qrCode,245, path);
            String qrCodeUrl = PropertiesUtil.getUrl(Constant.IMAGE_HOST,"qrcode")+"/"+file.getName();
            return Response.response(ResponseCode.SUCCESS,"统一下单成功",qrCodeUrl);
        }catch (Exception e){
            return Response.response(ResponseCode.ERROR,"生成二维码失败",null);
        }
    }

    public static void main(String[] args){
        FileService fileService = new FileService();
        LOGGER.info(fileService.saveQrCode("https://qr.alipay.com/bax00434do0anwi467bj0070","123432454"));
    }

}
